import { ref, reactive } from 'vue'
import { isCancel } from 'axios'
import Dayjs from 'dayjs'

export const useTable = function (apiFunc, noPage = false) {
  const tableData = ref([])
  const page_num = ref(1)
  const size = ref(10)
  const loading = ref(false)
  const total = ref(0)

  // 从 v0.22.0 开始，Axios 支持以 fetch API 方式—— AbortController 取消请求：
  let controller = new AbortController()
  function getData(params) {
    const obj = Object.assign(
      {
        page_num: page_num.value,
        size: size.value,
      },
      params,
    )
    if (loading.value) {
      // 请求正在进行中，取消掉，并重新new一个controller
      controller.abort()
      controller = new AbortController()
    }

    loading.value = true
    return apiFunc(obj, { signal: controller.signal })
      .then((res) => {
        if (noPage) {
          tableData.value = res.data || []
          return res.data
        }
        const { data_list = [], total: count = 0 } = res.data || {}
        tableData.value = data_list
        total.value = count
        return res.data
      })
      .catch((err) => {
        if (!isCancel(err)) {
          return Promise.reject(err)
        }
      })
      .finally(() => {
        loading.value = false
      })
  }
  return {
    tableData,
    page_num,
    size,
    loading,
    total,
    getData,
  }
}

export const useFilters = function (filters) {
  const params = reactive({})

  function init() {
    filters.forEach((v) => {
      if (typeof v.value === 'function') {
        params[v.key] = v.value()
      } else {
        params[v.key] = v.value
      }
    })
  }
  init()

  function getParams() {
    const obj = {}
    filters.forEach((v) => {
      if (v.type === 'datepicker') {
        const dProps = v.dynamicProps && v.dynamicProps(params);
        const dateType = v.props?.type || dProps?.type;
        switch (dateType) {
          case 'daterange':
            obj[v.startKey] = params[v.key] ? params[v.key][0] + (v.fixTime ? ' 00:00:00' : '') : null
            obj[v.endKey] = params[v.key] ? params[v.key][1] + (v.fixTime ? ' 23:59:59' : '') : null
            return
          case 'monthrange':
            obj[v.startKey] = params[v.key]
              ? (v.fixDay ? fixDay(params[v.key][0], 'start') : params[v.key][0])
              : null;
            obj[v.endKey] = params[v.key]
              ? (v.fixDay ? fixDay(params[v.key][1], 'end') : params[v.key][1])
              : null;
            return
          case 'datetimerange':
            obj[v.startKey] = params[v.key] ? params[v.key][0] : null
            obj[v.endKey] = params[v.key] ? params[v.key][1] : null
            return

        }
      }
      obj[v.key] = params[v.key]
    })
    return obj
  }

  return {
    params,
    getParams,
    reset: init,
  }
}

// 月份补充日期
function fixDay(month, type) {
  if (month.length === 7) {
    // 如果是 YYYY-MM 格式，补充为 YYYY-MM-01
    month += '-01';
  }
  if (type === 'start') {
    return month;
  } else if (type === 'end') {
    return Dayjs(month).endOf('month').format('YYYY-MM-DD');
  }
}

// export const useReactive = function (originObj) {
//   const cache = deepClone(originObj);
//   const proxy = reactive(originObj);
//   function assign(newObj) {
//     if (newObj === 'init') {
//       newObj = cache;
//     }
//     const keys = Object.keys(originObj);
//     keys.forEach((k) => {
//       proxy[k] = deepClone(newObj[k]) ?? cache[k];
//     });
//   }
//   return [proxy, assign];
// };
